<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>python基础学习笔记(一) | Ysnsn博客</title><meta name="keywords" content="python,笔记"><meta name="author" content="可爱的Wyang"><meta name="copyright" content="可爱的Wyang"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="description" content="只为记录我的学习过程中的示例及笔记，为自己日后复习使用">
<meta property="og:type" content="article">
<meta property="og:title" content="python基础学习笔记(一)">
<meta property="og:url" content="https://ysnsn.cn/python-study1.html">
<meta property="og:site_name" content="Ysnsn博客">
<meta property="og:description" content="只为记录我的学习过程中的示例及笔记，为自己日后复习使用">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/Ysnsn/picture@master/111/20200822112556.jpg">
<meta property="article:published_time" content="2020-08-22T02:47:43.000Z">
<meta property="article:modified_time" content="2020-09-13T12:21:36.177Z">
<meta property="article:author" content="可爱的Wyang">
<meta property="article:tag" content="python">
<meta property="article:tag" content="笔记">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/Ysnsn/picture@master/111/20200822112556.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://ysnsn.cn/python-study1.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css"><script>var GLOBAL_CONFIG = { 
  root: '/',
  hexoversion: '5.0.0',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":50,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  ClickShowText: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  justifiedGallery: {
    js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
    css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isanchor: false
};

var saveToLocal = {
  set: function setWithExpiry(key, value, ttl) {
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isSidebar: false,
  postUpdate: '2020-09-13 20:21:36'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {
  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }

  const autoChangeMode = 'true'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified

    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }
})()</script><meta name="generator" content="Hexo 5.0.0"><link rel="alternate" href="/atom.xml" title="Ysnsn博客" type="application/atom+xml">
</head><body><div id="mobile-sidebar"><div id="menu_mask"></div><div id="mobile-sidebar-menus"><div class="mobile_author_icon"><img class="avatar-img" src="/img/avatar.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="mobile_post_data"><div class="mobile_data_item is-center"><div class="mobile_data_link"><a href="/archives/"><div class="headline">文章</div><div class="length_num">15</div></a></div></div><div class="mobile_data_item is-center">      <div class="mobile_data_link"><a href="/tags/"><div class="headline">标签</div><div class="length_num">26</div></a></div></div><div class="mobile_data_item is-center">     <div class="mobile_data_link"><a href="/categories/"><div class="headline">分类</div><div class="length_num">8</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fas fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/mikutap/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></div><div class="menus_item"><a class="site-page" href="/bangumis/"><i class="fa-fw fas fa-cocktail"></i><span> 哔哩哔哩</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-inbox"></i><span> 基地</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page" target="_blank" rel="noopener" href="https://ysnsn.herokuapp.com/"><i class="fa-fw fas fa-cloud-download-alt"></i><span> 网盘OM</span></a></li><li><a class="site-page" target="_blank" rel="noopener" href="http://tc.ysnsn.cn/"><i class="fa-fw fas fa-paper-plane"></i><span> 立即前往</span></a></li><li><a class="site-page" target="_blank" rel="noopener" href="http://zz.ysnsn.cn/"><i class="fa-fw fas fa-feather"></i><span> Donate</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-gavel"></i><span> 小应用</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/silk/"><i class="fa-fw fas fa-signature"></i><span> 丝画silk</span></a></li><li><a class="site-page" href="/caidie/"><i class="fa-fw fas fa-bug"></i><span> 彩蝶</span></a></li><li><a class="site-page" href="/%E6%B6%B2%E4%BD%93/"><i class="fa-fw fas fa-bullseye"></i><span> 液体</span></a></li><li><a class="site-page" href="/smail/"><i class="fa-fw fas fa-democrat"></i><span> 笑脸滑稽</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 菜单</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page" href="/gallery/"><i class="fa-fw fas fa-camera"></i><span> 相册</span></a></li><li><a class="site-page" href="/sc/"><i class="fa-fw fas fa-key"></i><span> 每日诗词</span></a></li><li><a class="site-page" href="/wysp/"><i class="fa-fw fas fa-fire"></i><span> 网易热评</span></a></li></ul></div></div></div></div><div id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(https://cdn.jsdelivr.net/gh/Ysnsn/picture@master/111/20200822112556.jpg)"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Ysnsn博客</a></span><span id="menus"><div id="search_button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fas fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/mikutap/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></div><div class="menus_item"><a class="site-page" href="/bangumis/"><i class="fa-fw fas fa-cocktail"></i><span> 哔哩哔哩</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-inbox"></i><span> 基地</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page" target="_blank" rel="noopener" href="https://ysnsn.herokuapp.com/"><i class="fa-fw fas fa-cloud-download-alt"></i><span> 网盘OM</span></a></li><li><a class="site-page" target="_blank" rel="noopener" href="http://tc.ysnsn.cn/"><i class="fa-fw fas fa-paper-plane"></i><span> 立即前往</span></a></li><li><a class="site-page" target="_blank" rel="noopener" href="http://zz.ysnsn.cn/"><i class="fa-fw fas fa-feather"></i><span> Donate</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-gavel"></i><span> 小应用</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/silk/"><i class="fa-fw fas fa-signature"></i><span> 丝画silk</span></a></li><li><a class="site-page" href="/caidie/"><i class="fa-fw fas fa-bug"></i><span> 彩蝶</span></a></li><li><a class="site-page" href="/%E6%B6%B2%E4%BD%93/"><i class="fa-fw fas fa-bullseye"></i><span> 液体</span></a></li><li><a class="site-page" href="/smail/"><i class="fa-fw fas fa-democrat"></i><span> 笑脸滑稽</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 菜单</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page" href="/gallery/"><i class="fa-fw fas fa-camera"></i><span> 相册</span></a></li><li><a class="site-page" href="/sc/"><i class="fa-fw fas fa-key"></i><span> 每日诗词</span></a></li><li><a class="site-page" href="/wysp/"><i class="fa-fw fas fa-fire"></i><span> 网易热评</span></a></li></ul></div></div><span class="close" id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></span></span></nav><div id="post-info"><div id="post-title"><div class="posttitle">python基础学习笔记(一)</div></div><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-08-22T02:47:43.000Z" title="发表于 2020-08-22 10:47:43">2020-08-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-09-13T12:21:36.177Z" title="更新于 2020-09-13 20:21:36">2020-09-13</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a></span></div><div class="meta-secondline"> <span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>9分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/python-study1.html#post-comment" itemprop="discussionUrl"><span class="valine-comment-count comment-count" data-xid="/python-study1.html" itemprop="commentCount"></span></a></span></div></div></div></header><main class="layout_post" id="content-inner"><article id="post"><div class="post-content" id="article-container"><blockquote>
<h2 id="🥢学习途径">🥢学习途径</h2>
</blockquote>
<ol>
<li>
<p>mooc嵩天  <a target="_blank" rel="noopener" href="https://www.icourse163.org/learn/BIT-1002058035?tid=1002161029#/learn/announce">https://www.icourse163.org/learn/BIT-1002058035?tid=1002161029#/learn/announce</a></p>
</li>
<li>
<p>B站 用来的学习网站（没说错吧）</p>
</li>
<li>
<p>python100天  <a target="_blank" rel="noopener" href="https://github.com/jackfrued/Python-100-Days">https://github.com/jackfrued/Python-100-Days</a></p>
</li>
<li>
<p>python菜鸟教程  <a target="_blank" rel="noopener" href="https://www.runoob.com/python/python-tutorial.html">https://www.runoob.com/python/python-tutorial.html</a></p>
</li>
<li>
<p>淘宝买的二级书</p>
</li>
</ol>
<h2 id="🍬软件使用">🍬软件使用</h2>
<ol>
<li>
<p>官网python版本一般用3.7.0   <a target="_blank" rel="noopener" href="https://www.python.org/">https://www.python.org/</a></p>
</li>
<li>
<p>vscode 装了插件后好看用  <a target="_blank" rel="noopener" href="https://code.visualstudio.com/">https://code.visualstudio.com/</a></p>
</li>
<li>
<p>推荐使用<a target="_blank" rel="noopener" href="https://www.sublimetext.com/">Sublime</a></p>
</li>
</ol>
<h2 id="✅重点记录">✅重点记录</h2>
<ol>
<li>重复元素判定</li>
</ol>
<p>以下方法可以检查给定列表是不是存在重复元素，它会使用 set() 函数来移除所有重复元素。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">def all_unique(lst):</span><br><span class="line">return len(lst)&#x3D;&#x3D; len(set(lst))</span><br><span class="line">x &#x3D; [1,1,2,2,3,2,3,4,5,6]</span><br><span class="line">y &#x3D; [1,2,3,4,5]</span><br><span class="line">all_unique(x) # False</span><br><span class="line">all_unique(y) # True</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>字符元素组成判定</li>
</ol>
<p>检查两个字符串的组成元素是不是一样的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">from collections import Counter</span><br><span class="line">def anagram(first, second):</span><br><span class="line">return Counter(first) &#x3D;&#x3D; Counter(second)</span><br><span class="line">anagram(&quot;abcd3&quot;, &quot;3acdb&quot;) # True</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>内存占用</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">import sys</span><br><span class="line">variable &#x3D; 30</span><br><span class="line">print(sys.getsizeof(variable)) # 24</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>字节占用</li>
</ol>
<p>下面的代码块可以检查字符串占用的字节数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">def byte_size(string):</span><br><span class="line">return(len(string.encode(&#39;utf-8&#39;)))</span><br><span class="line">byte_size(&#39;&#39;) # 4</span><br><span class="line">byte_size(&#39;Hello World&#39;) # 11</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>打印 N 次字符串</li>
</ol>
<p>该代码块不需要循环语句就能打印 N 次字符串。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">n &#x3D; 2</span><br><span class="line">s &#x3D;&quot;Programming&quot;</span><br><span class="line">print(s * n)</span><br><span class="line"># ProgrammingProgramming</span><br></pre></td></tr></table></figure>
<p>6 大写第一个字母</p>
<p>以下代码块会使用 title() 方法，从而大写字符串中每一个单词的首字母。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">s &#x3D; &quot;programming is awesome&quot;</span><br><span class="line">print(s.title())</span><br><span class="line"># Programming Is Awesome</span><br></pre></td></tr></table></figure>
<ol start="7">
<li>分块</li>
</ol>
<p>给定具体的大小，定义一个函数以按照这个大小切割列表。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">from math import ceil</span><br><span class="line">def chunk(lst, size):</span><br><span class="line">return list(</span><br><span class="line">map(lambda x: lst[x * size:x * size + size],</span><br><span class="line">list(range(0, ceil(len(lst) &#x2F; size)))))</span><br><span class="line">chunk([1,2,3,4,5],2)</span><br><span class="line"># [[1,2],[3,4],5]</span><br></pre></td></tr></table></figure>
<ol start="8">
<li>压缩</li>
</ol>
<p>这个方法可以将布尔型的值去掉，例如（False，None，0，“”），它使用 filter() 函数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">def compact(lst):</span><br><span class="line">return list(filter(bool, lst))</span><br><span class="line">compact([0, 1, False, 2, &#39;&#39;, 3, &#39;a&#39;, &#39;s&#39;, 34])</span><br><span class="line"># [ 1, 2, 3, &#39;a&#39;, &#39;s&#39;, 34 ]</span><br></pre></td></tr></table></figure>
<ol start="9">
<li>解包</li>
</ol>
<p>如下代码段可以将打包好的成对列表解开成两组不同的元组。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">array &#x3D; [[&#39;a&#39;, &#39;b&#39;], [&#39;c&#39;, &#39;d&#39;], [&#39;e&#39;, &#39;f&#39;]]</span><br><span class="line">transposed &#x3D; zip(*array)</span><br><span class="line">print(transposed)</span><br><span class="line"># [(&#39;a&#39;, &#39;c&#39;, &#39;e&#39;), (&#39;b&#39;, &#39;d&#39;, &#39;f&#39;)]</span><br></pre></td></tr></table></figure>
<ol start="10">
<li>链式对比</li>
</ol>
<p>我们可以在一行代码中使用不同的运算符对比多个不同的元素。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a &#x3D; 3</span><br><span class="line">print( 2 &lt; a &lt; 8) # True</span><br><span class="line">print(1 &#x3D;&#x3D; a &lt; 2) # False</span><br></pre></td></tr></table></figure>
<ol start="11">
<li>逗号连接</li>
</ol>
<p>下面的代码可以将列表连接成单个字符串，且每一个元素间的分隔方式设置为了逗号。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">hobbies &#x3D; [&quot;basketball&quot;, &quot;football&quot;, &quot;swimming&quot;]</span><br><span class="line">print(&quot;My hobbies are: &quot; + &quot;, &quot;.join(hobbies))</span><br><span class="line"># My hobbies are: basketball, football, swimming</span><br></pre></td></tr></table></figure>
<ol start="12">
<li>元音统计</li>
</ol>
<p>以下方法将统计字符串中的元音 (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) 的个数，它是通过正则表达式做的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">import re</span><br><span class="line">def count_vowels(str):</span><br><span class="line">return len(len(re.findall(r&#39;[aeiou]&#39;, str, re.IGNORECASE)))</span><br><span class="line">count_vowels(&#39;foobar&#39;) # 3</span><br><span class="line">count_vowels(&#39;gym&#39;) # 0</span><br></pre></td></tr></table></figure>
<ol start="13">
<li>首字母小写</li>
</ol>
<p>如下方法将令给定字符串的第一个字符统一为小写。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">def decapitalize(string):</span><br><span class="line">return str[:1].lower() + str[1:]</span><br><span class="line">decapitalize(&#39;FooBar&#39;) # &#39;fooBar&#39;</span><br><span class="line">decapitalize(&#39;FooBar&#39;) # &#39;fooBar&#39;</span><br></pre></td></tr></table></figure>
<ol start="14">
<li>展开列表</li>
</ol>
<p>该方法将通过递归的方式将列表的嵌套展开为单个列表。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">def spread(arg):</span><br><span class="line">ret &#x3D; []</span><br><span class="line">for i in arg:</span><br><span class="line">if isinstance(i, list):</span><br><span class="line">ret.extend(i)</span><br><span class="line">else:</span><br><span class="line">ret.append(i)</span><br><span class="line">return ret</span><br><span class="line">def deep_flatten(lst):</span><br><span class="line">result &#x3D; []</span><br><span class="line">result.extend(</span><br><span class="line">spread(list(map(lambda x: deep_flatten(x) if type(x) &#x3D;&#x3D; list else x, lst))))</span><br><span class="line">return result</span><br><span class="line">deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]</span><br></pre></td></tr></table></figure>
<ol start="15">
<li>列表的差</li>
</ol>
<p>该方法将返回第一个列表的元素，其不在第二个列表内。如果同时要反馈第二个列表独有的元素，还需要加一句 set_b.difference(set_a)。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">def difference(a, b):</span><br><span class="line">set_a &#x3D; set(a)</span><br><span class="line">set_b &#x3D; set(b)</span><br><span class="line">comparison &#x3D; set_a.difference(set_b)</span><br><span class="line">return list(comparison)</span><br><span class="line">difference([1,2,3], [1,2,4]) # [3]</span><br></pre></td></tr></table></figure>
<ol start="16">
<li>通过函数取差</li>
</ol>
<p>如下方法首先会应用一个给定的函数，然后再返回应用函数后结果有差别的列表元素。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">def difference_by(a, b, fn):</span><br><span class="line">b &#x3D; set(map(fn, b))</span><br><span class="line">return [item for item in a if fn(item) not in b]</span><br><span class="line">from math import floor</span><br><span class="line">difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]</span><br><span class="line">difference_by([&#123; &#39;x&#39;: 2 &#125;, &#123; &#39;x&#39;: 1 &#125;], [&#123; &#39;x&#39;: 1 &#125;], lambda v : v[&#39;x&#39;])</span><br><span class="line"># [ &#123; x: 2 &#125; ]</span><br></pre></td></tr></table></figure>
<ol start="17">
<li>链式函数调用</li>
</ol>
<p>你可以在一行代码内调用多个函数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">def add(a, b):</span><br><span class="line">return a + b</span><br><span class="line">def subtract(a, b):</span><br><span class="line">return a - b</span><br><span class="line">a, b &#x3D; 4, 5</span><br><span class="line">print((subtract if a &gt; b else add)(a, b)) # 9</span><br></pre></td></tr></table></figure>
<ol start="18">
<li>检查重复项</li>
</ol>
<p>如下代码将检查两个列表是不是有重复项。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">def has_duplicates(lst):</span><br><span class="line">return len(lst) !&#x3D; len(set(lst))</span><br><span class="line">x &#x3D; [1,2,3,4,5,5]</span><br><span class="line">y &#x3D; [1,2,3,4,5]</span><br><span class="line">has_duplicates(x) # True</span><br><span class="line">has_duplicates(y) # False</span><br></pre></td></tr></table></figure>
<ol start="19">
<li>合并两个字典</li>
</ol>
<p>下面的方法将用于合并两个字典。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">def merge_two_dicts(a, b):</span><br><span class="line">c &#x3D; a.copy() # make a copy of a </span><br><span class="line">c.update(b) # modify keys and values of a with the once from b</span><br><span class="line">return c</span><br><span class="line">a&#x3D;&#123;&#39;x&#39;:1,&#39;y&#39;:2&#125;</span><br><span class="line">b&#x3D;&#123;&#39;y&#39;:3,&#39;z&#39;:4&#125;</span><br><span class="line">print(merge_two_dicts(a,b))</span><br><span class="line">#&#123;&#39;y&#39;:3,&#39;x&#39;:1,&#39;z&#39;:4&#125;</span><br></pre></td></tr></table></figure>
<p>在 Python 3.5 或更高版本中，我们也可以用以下方式合并字典：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">def merge_dictionaries(a, b)</span><br><span class="line">return &#123;**a, **b&#125;</span><br><span class="line">a &#x3D; &#123; &#39;x&#39;: 1, &#39;y&#39;: 2&#125;</span><br><span class="line">b &#x3D; &#123; &#39;y&#39;: 3, &#39;z&#39;: 4&#125;</span><br><span class="line">print(merge_dictionaries(a, b))</span><br><span class="line"># &#123;&#39;y&#39;: 3, &#39;x&#39;: 1, &#39;z&#39;: 4&#125;</span><br></pre></td></tr></table></figure>
<ol start="20">
<li>将两个列表转化为字典</li>
</ol>
<p>如下方法将会把两个列表转化为单个字典。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">def to_dictionary(keys, values):</span><br><span class="line">return dict(zip(keys, values))</span><br><span class="line">keys &#x3D; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]</span><br><span class="line">values &#x3D; [2, 3, 4]</span><br><span class="line">print(to_dictionary(keys, values))</span><br><span class="line">#&#123;&#39;a&#39;: 2, &#39;c&#39;: 4, &#39;b&#39;: 3&#125;</span><br></pre></td></tr></table></figure>
<ol start="21">
<li>使用枚举</li>
</ol>
<p>我们常用 For 循环来遍历某个列表，同样我们也能枚举列表的索引与值。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">list &#x3D; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]</span><br><span class="line">for index, element in enumerate(list): </span><br><span class="line">print(&quot;Value&quot;, element, &quot;Index &quot;, index, )</span><br><span class="line"># (&#39;Value&#39;, &#39;a&#39;, &#39;Index &#39;, 0)</span><br><span class="line"># (&#39;Value&#39;, &#39;b&#39;, &#39;Index &#39;, 1)</span><br><span class="line">#(&#39;Value&#39;, &#39;c&#39;, &#39;Index &#39;, 2)</span><br><span class="line"># (&#39;Value&#39;, &#39;d&#39;, &#39;Index &#39;, 3)</span><br></pre></td></tr></table></figure>
<ol start="22">
<li>执行时间</li>
</ol>
<p>如下代码块可以用来计算执行特定代码所花费的时间。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">import time</span><br><span class="line">start_time &#x3D; time.time()</span><br><span class="line">a &#x3D; 1</span><br><span class="line">b &#x3D; 2</span><br><span class="line">c &#x3D; a + b</span><br><span class="line">print(c) #3</span><br><span class="line">end_time &#x3D; time.time()</span><br><span class="line">total_time &#x3D; end_time - start_time</span><br><span class="line">print(&quot;Time: &quot;, total_time)</span><br><span class="line"># (&#39;Time: &#39;, 1.1205673217773438e-05) </span><br></pre></td></tr></table></figure>
<ol start="23">
<li>Try else</li>
</ol>
<p>我们在使用 try/except 语句的时候也可以加一个 else 子句，如果没有触发错误的话，这个子句就会被运行。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">try:</span><br><span class="line">2*3</span><br><span class="line">except TypeError:</span><br><span class="line">print(&quot;An exception was raised&quot;)</span><br><span class="line">else:</span><br><span class="line">print(&quot;Thank God, no exceptions were raised.&quot;)</span><br><span class="line">#Thank God, no exceptions were raised.</span><br></pre></td></tr></table></figure>
<ol start="24">
<li>元素频率</li>
</ol>
<p>下面的方法会根据元素频率取列表中最常见的元素。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">def most_frequent(list):</span><br><span class="line">return max(set(list), key &#x3D; list.count)</span><br><span class="line">list &#x3D; [1,2,1,2,3,2,1,4,2]</span><br><span class="line">most_frequent(list)</span><br></pre></td></tr></table></figure>
<ol start="25">
<li>回文序列</li>
</ol>
<p>以下方法会检查给定的字符串是不是回文序列，它首先会把所有字母转化为小写，并移除非英文字母符号。最后，它会对比字符串与反向字符串是否相等，相等则表示为回文序列。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">def palindrome(string):</span><br><span class="line">from re import sub</span><br><span class="line">s &#x3D; sub(&#39;[\W_]&#39;, &#39;&#39;, string.lower())</span><br><span class="line">return s &#x3D;&#x3D; s[::-1]</span><br><span class="line">palindrome(&#39;taco cat&#39;) # True</span><br></pre></td></tr></table></figure>
<ol start="26">
<li>不使用 if-else 的计算子</li>
</ol>
<p>这一段代码可以不使用条件语句就实现加减乘除、求幂操作，它通过字典这一数据结构实现：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">import operator</span><br><span class="line">action &#x3D; &#123;</span><br><span class="line">&quot;+&quot;: operator.add,</span><br><span class="line">&quot;-&quot;: operator.sub,</span><br><span class="line">&quot;&#x2F;&quot;: operator.truediv,</span><br><span class="line">&quot;*&quot;: operator.mul,</span><br><span class="line">&quot;**&quot;: pow</span><br><span class="line">&#125;</span><br><span class="line">print(action[&#39;-&#39;](50, 25)) # 25</span><br></pre></td></tr></table></figure>
<ol start="27">
<li>Shuffle</li>
</ol>
<p>该算法会打乱列表元素的顺序，它主要会通过 Fisher-Yates 算法对新列表进行排序：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">from copy import deepcopy</span><br><span class="line">from random import randint</span><br><span class="line">def shuffle(lst):</span><br><span class="line">temp_lst &#x3D; deepcopy(lst)</span><br><span class="line">m &#x3D; len(temp_lst)</span><br><span class="line">while (m):</span><br><span class="line">m -&#x3D; 1</span><br><span class="line">i &#x3D; randint(0, m)</span><br><span class="line">temp_lst[m], temp_lst[i] &#x3D; temp_lst[i], temp_lst[m]</span><br><span class="line">return temp_lst</span><br><span class="line">foo &#x3D; [1,2,3]</span><br><span class="line">shuffle(foo) # [2,3,1] , foo &#x3D; [1,2,3]</span><br></pre></td></tr></table></figure>
<ol start="28">
<li>展开列表</li>
</ol>
<p>将列表内的所有元素，包括子列表，都展开成一个列表。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">def spread(arg):</span><br><span class="line">ret &#x3D; []</span><br><span class="line">for i in arg:if isinstance(i, list):</span><br><span class="line">ret.extend(i)</span><br><span class="line">else:</span><br><span class="line">ret.append(i)</span><br><span class="line">return ret</span><br><span class="line">spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]</span><br></pre></td></tr></table></figure>
<ol start="29">
<li>交换值</li>
</ol>
<p>不需要额外的操作就能交换两个变量的值。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">def swap(a, b):</span><br><span class="line">return b, a</span><br><span class="line">a, b &#x3D; -1, 14</span><br><span class="line">swap(a, b) # (14, -1)</span><br><span class="line">spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]</span><br></pre></td></tr></table></figure>
<ol start="30">
<li>字典默认值</li>
</ol>
<p>通过 Key 取对应的 Value 值，可以通过以下方式设置默认值。如果 get() 方法没有设置默认值，那么如果遇到不存在的 Key，则会返回 None。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">d &#x3D; &#123;&#39;a&#39;: 1, &#39;b&#39;: 2&#125;</span><br><span class="line">print(d.get(&#39;c&#39;, 3)) # 3</span><br></pre></td></tr></table></figure>
</div><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">可爱的Wyang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://ysnsn.cn/python-study1.html">https://ysnsn.cn/python-study1.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://ysnsn.cn" target="_blank">Ysnsn博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/python/">python</a><a class="post-meta__tags" href="/tags/%E7%AC%94%E8%AE%B0/">笔记</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/Ysnsn/picture@master/111/20200822112556.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏<div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li><li class="reward-item"><a href="/img/qq.jpg" target="_blank"><img class="post-qr-code-img" src="/img/qq.jpg" alt="QQ"/></a><div class="post-qr-code-desc">QQ</div></li></ul></div></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2817.html"><img class="prev-cover" src="https://cdn.jsdelivr.net/gh/Ysnsn/picture@master/111/20200822141843.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">如何快速拥有自己的百度网盘网页版下载</div></div></a></div><div class="next-post pull-right"><a href="/GitHub-jsdelivr.html"><img class="next-cover" src="https://cdn.jsdelivr.net/gh/Ysnsn/picture@master/11120200821181132.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">jsdelivr的正确使用方法</div></div></a></div></nav><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></article></main><footer id="footer" style="background-image: url(https://cdn.jsdelivr.net/gh/Ysnsn/picture@master/111/20200822112556.jpg)"><div id="footer-wrap"><div class="copyright">&copy;2020 By 可爱的Wyang</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">相信自己，一往无前</div><div class="icp"><a target="_blank" rel="noopener" href="https://icp.gov.moe/join.html"><img class="icp-icon" src="/img/icp.png"/><span>萌ICP备20201314号</span></a></div><div id="running-time"></div><script>setInterval(()=>{let create_time=Math.round(new Date(Date.UTC(2020,06,23,0,0,0)).getTime()/1000);let timestamp=Math.round((new Date().getTime()+8*60*60*1000)/1000);let second=timestamp-create_time;let time=new Array(0,0,0,0,0);if(second>=365*24*3600){time[0]=parseInt(second/(365*24*3600));second%=365*24*3600;}if(second>=24*3600){time[1]=parseInt(second/(24*3600));second%=24*3600;}if(second>=3600){time[2]=parseInt(second/3600);second%=3600;}if(second>=60){time[3]=parseInt(second/60);second%=60;}if(second>0){time[4]=second;}currentTimeHtml='🌈本站已安全运行 '+time[0]+' 年 '+time[1]+' 天 '+time[2]+' 时 '+time[3]+' 分 '+time[4]+' 秒';document.getElementById("running-time").innerHTML=currentTimeHtml;},1000);</script></div></footer></div><section id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></section><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div><div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    window.valine = new Valine({
      el: '#vcomment',
      master:'09baf6c84634876ef43dfb5b5e7527cd',
      friends:'0fa72164d542c33924ec89694aad4616,ad10871ff24424bf880b4cbbde9e0c6b',
      appId: 'pE6fuMFtYcEgYTceSY23YlFs-MdYXbMMI',
      appKey: 'GwiyT9FTAXYmRfkn24oywXtu',
      placeholder: '🤳昵称框输入QQ号自动获取QQ图像 \n🚩使用Akismet反垃圾评论 \n🌈支持md语法，请尽情表演吧 \n🛴邮件通知时间为8点到24点',
      avatar: 'monsterid',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: true,
      serverURLs: '',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: true,
      path: window.location.pathname,
    });
    if ('nick,mail') { valine.config.requiredFields= 'nick,mail'.split(',') }
  }

  if (typeof Valine === 'function') initValine() 
  else $.getScript('https://cdn.jsdelivr.net/gh/lete114/CDN2/js/Valine-Lete3.2.js', initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.querySelector('#vcomment'),loadValine)
  else setTimeout(() => loadValine(), 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script src="https://cdn.jsdelivr.net/npm/blueimp-md5@2.17.0/js/md5.min.js"></script><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<[^>]+>/g,"") // remove html tag
    content = content.replace(/(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|jpeg|gif|png|webp)/g, '') // remove image link
    content = content.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi, '') // remove url

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getIcon = (icon, mail) => {
    if (icon) return icon 
    let defaultIcon = ''
    let iconUrl = `https://gravatar.loli.net/avatar/${md5(mail.toLowerCase()) + defaultIcon}`
    return iconUrl
  }

  const generateHtml = array => {
    let result = ''

    for (let i = 0; i < array.length; i++) {
      result += '<div class=\'aside-list-item\'>'

      if (true) {
        result += `<a href='${array[i].url}' class="thumbnail"><img src='${getIcon(array[i].avatar, array[i].mail)}' alt='${array[i].nick}'></a>`
      }

      result += `<div class='content'>
      <a class='comment' href='${array[i].url}'>${array[i].content}</a>
      <div class='name'><span>${array[i].nick}</span><time> / ${btf.diffDate(array[i].date, true)}</time></div>
      </div></div>`
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.pjax && window.pjax.refresh($dom)
  }

  const getValineData = () => {
      let serverURL = ''
      if (false) {
        serverURL = ''
      } else {
        serverURL = 'https://pE6fuMFt.api.lncldglobal.com'
      }

    var settings = {
      "url": `${serverURL}/1.1/classes/Comment?limit=6&order=-createdAt`,
      "method": "GET",
      "timeout": 0,
      "headers": {
        "X-LC-Id": 'pE6fuMFtYcEgYTceSY23YlFs-MdYXbMMI',
        "X-LC-Key": 'GwiyT9FTAXYmRfkn24oywXtu',
        "Content-Type": "application/json"
      },
    }

    $.ajax(settings).done((response) => {
      var valineArray = []
      response.results.forEach((e)=>{
        valineArray.push({
          'avatar': e.QQAvatar,
          'content': changeContent(e.comment),
          'mail': e.mail,
          'nick': e.nick,
          'url': e.url,
          'date': e.createdAt,
        })
      })
      
      saveToLocal.set('leancloud-newest-comments', JSON.stringify(valineArray), 10/(60*24))
      generateHtml(valineArray)

    }).fail(()=>{
      const $dom = document.querySelector('#card-newest-comments .aside-list')
      $dom.innerHTML= "无法获取资料，请确认相关配置是否正确"
    })
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('leancloud-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getValineData()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><script src="https://myhkw.cn/player/js/player.js" id="myhk" key="159585720839" m="1"></script><link rel="stylesheet" href="/css/ysnsn.css"><script src="/js/ysnsn.js"></script><script src="https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/js/mouse_snow.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config_change',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  $('script[data-pjax]').each(function () {
    $(this).parent().append($(this).remove())
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  if (typeof gtag === 'function') {
    gtag('config', '', {'page_path': window.location.pathname});
  }

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})


document.addEventListener('pjax:send', function () {
  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  $(window).off('scroll')

  //reset readmode
  $('body').hasClass('read-mode') && $('body').removeClass('read-mode')

})</script></div><script src="/live2d/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2d/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"display":{"position":"left"},"mobile":{"show":false},"model":{"scale":1.2,"jsonPath":"/live2d/assets/weier.model.json"},"log":false});</script></body></html>